<?php

namespace api\modules\v1\controllers;


use api\modules\models\LoginForm;
use api\modules\v1\base\RestApiBaseController;
use api\modules\commons\Func;
use mdm\admin\components\MenuHelper;
use mdm\admin\models\Menu as MenuModel;
use mdm\admin\models\Route;
use Yii;

/**
 * @package Petstore30\controllers
 *
 * @author  Donii Sergii <doniysa@gmail.com>
 *
 * @OA\Tag(
 *     name="用户管理",
 *     description="用户管理接口文档",
 *     *
 * )
 */
class UserController extends RestApiBaseController
{
    /**
     * @OA\Post(
     *     path="/v1/user/login",
     *     tags={"用户管理"},
     *     summary="登录",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(
     *                     property="username",
     *                     type="string"
     *                 ),
     *                 @OA\Property(
     *                     property="password",
     *                     type="string"
     *                 ),
     *                 example={"username": "admin", "password": "swagger_element"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     )
     * )
     */
    public function actionLogin()
    {
        if (!Yii::$app->request->isPost) {
            return $this->fail('请以POST方式请求', [], '');
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->getBodyParams(), '') && $model->login()) {
            $data =  ['token'=>$model->access_token];
            return $this->success($data, '', '登录成功');
        } else {
            return $this->fail($model->getFirstErrors());
        }
    }

    /**
     * @OA\Post(
     *     path="/v1/user/add",
     *     tags={"用户管理"},
     *     summary="添加用户",
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(
     *                     property="id",
     *                     type="string"
     *                 ),
     *                 @OA\Property(
     *                     property="name",
     *                     type="string"
     *                 ),
     *                 example={"id": 10, "name": "Jessica Smith"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     )
     * )
     */
    public function actionAdd() {
        return ['code'=>0, 'msg'=>'添加用户成功'];
    }

    /**
     * @OA\Put(
     *     path="/v1/user/index",
     *     tags={"用户管理"},
     *     summary="Index",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=400,
     *         description="Invalid ID supplied"
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Pet not found"
     *     ),
     *     @OA\Response(
     *         response=405,
     *         description="Validation exception"
     *     ),
     *     security={
     *         {"petstore_auth": {"write:pets", "read:pets"}}
     *     },
     *     @OA\Response(
     *         response=200,
     *         description="successful operation"
     *     ),
     * )
     */
    public function actionIndex()
    {
        return $this->success(Yii::$app->user->identity->toArray());
    }

    /*public function actionIndex()
    {
        $fex = '/' . $this->module->id;
        return $this->success($this->getRouts($fex));
    }*/
    // 获取系统全部路由，并按照当前模块，进行过滤
    private function getRouts($fex='') {
        $routes = (new Route())->getRoutes();

        $available = [];
        foreach ($routes['available'] as $av_route) {
            if ($fex) {
                $_fex = substr($av_route, 0,4);
                if ($_fex == $fex) {
                    $available[] = $av_route;
                }
            }else {
                $available[] = $av_route;
            }
        }
        $assigned = [];
        foreach ($routes['assigned'] as $as_route) {
            if ($fex) {
                $_fex = substr($as_route, 0,4);
                if ($_fex == $fex) {
                    $assigned[] = $as_route;
                }
            }else {
                $assigned[] = $as_route;
            }
        }

        return [
            'available' => $available,
            'assigned' => $assigned
        ];
    }

    /**
     * @OA\Post(
     *     path="/v1/user/register",
     *     tags={"用户管理"},
     *     summary="用户注册",
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(
     *                     property="username",
     *                     type="string"
     *                 ),
     *                 @OA\Property(
     *                     property="phone",
     *                     type="string"
     *                 ),
     *                 @OA\Property(
     *                     property="password",
     *                     type="string"
     *                 ),
     *                 example={"username": "用户名", "phone": "联系电话", "password": "登录密码"}
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionRegister() {
        return $this->success(['msg' => '用户注册接口待开发']);
    }

    /**
     * 用户信息
     *
     * @param string $id
     * @return array
     */
    /**
     * @OA\Get(
     *     path="/v1/user/info",
     *     tags={"用户管理"},
     *     summary="获取用户信息",
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="用于ID",
     *         required=true,
     *         @OA\Schema(
     *             type="integer",
     *             format="int64"
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionInfo()
    {
        if (Yii::$app->user->isGuest) {
            return $this->fail('未登录', []);
        }else {
            $data = Yii::$app->user->identity->toArray();
            $data['roles'] = ['Admin'];
            $data['avatar'] = '';
            $data['role'] = [
                'id' => 'admin',
                'name' => '管理员',
                'describe' => '拥有所有权限',
                'status' => 1,
                'creatorId' => 'system',
                'createTime' => 1497160610259,
                'deleted' => 0,
                'permissions' => []
            ];
            return $this->success($data, '', '登录用户信息');
        }
    }

    // 用户权限
    /**
     * @OA\Get(
     *     path="/v1/user/route",
     *     tags={"用户管理"},
     *     summary="用户权限",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionRoute() {
        $data = [
            [
                "path" =>  "/permission",
                "redirect" =>  "/permission/page",
                "alwaysShow" =>  true,
                "name" =>  "Permission",
                "meta" =>  [
                    "title" =>  "Permission",
                    "icon" =>  "lock",
                    "roles" =>  [
                        "admin",
                        "editor"
                    ]
                ],
                "children" =>  [
                    [
                        "path" =>  "page",
                        "name" =>  "PagePermission",
                        "meta" =>  [
                            "title" =>  "Page Permission",
                            "roles" =>  [
                                "admin"
                            ]
                        ]
                    ],
                    [
                        "path" =>  "directive",
                        "name" =>  "DirectivePermission",
                        "meta" =>  [
                            "title" =>  "Directive Permission"
                        ]
                    ],
                    [
                        "path" =>  "role",
                        "name" =>  "RolePermission",
                        "meta" =>  [
                            "title" =>  "Role Permission",
                            "roles" =>  [
                                "admin"
                            ]
                        ]
                    ]
                ]
            ],
            [
                "path" =>  "/icon",
                "children" =>  [
                    [
                        "path" =>  "index",
                        "name" =>  "Icons",
                        "meta" =>  [
                            "title" =>  "Icons",
                            "icon" =>  "icon",
                            "noCache" =>  true
                        ]
                    ]
                ]
            ],
            [
                "path" =>  "/components",
                "redirect" =>  "noRedirect",
                "name" =>  "ComponentDemo",
                "meta" =>  [
                    "title" =>  "Components",
                    "icon" =>  "component"
                ],
                "children" =>  [
                    [
                        "path" =>  "tinymce",
                        "name" =>  "TinymceDemo",
                        "meta" =>  [
                            "title" =>  "Tinymce"
                        ]
                    ],
                    [
                        "path" =>  "markdown",
                        "name" =>  "MarkdownDemo",
                        "meta" =>  [
                            "title" =>  "Markdown"
                        ]
                    ],
                    [
                        "path" =>  "json-editor",
                        "name" =>  "JsonEditorDemo",
                        "meta" =>  [
                            "title" =>  "JSON Editor"
                        ]
                    ],
                    [
                        "path" =>  "split-pane",
                        "name" =>  "SplitpaneDemo",
                        "meta" =>  [
                            "title" =>  "SplitPane"
                        ]
                    ],
                    [
                        "path" =>  "avatar-upload",
                        "name" =>  "AvatarUploadDemo",
                        "meta" =>  [
                            "title" =>  "Upload"
                        ]
                    ],
                    [
                        "path" =>  "dropzone",
                        "name" =>  "DropzoneDemo",
                        "meta" =>  [
                            "title" =>  "Dropzone"
                        ]
                    ],
                    [
                        "path" =>  "sticky",
                        "name" =>  "StickyDemo",
                        "meta" =>  [
                            "title" =>  "Sticky"
                        ]
                    ],
                    [
                        "path" =>  "count-to",
                        "name" =>  "CountToDemo",
                        "meta" =>  [
                            "title" =>  "Count To"
                        ]
                    ],
                    [
                        "path" =>  "mixin",
                        "name" =>  "ComponentMixinDemo",
                        "meta" =>  [
                            "title" =>  "Component Mixin"
                        ]
                    ],
                    [
                        "path" =>  "back-to-top",
                        "name" =>  "BackToTopDemo",
                        "meta" =>  [
                            "title" =>  "Back To Top"
                        ]
                    ],
                    [
                        "path" =>  "drag-dialog",
                        "name" =>  "DragDialogDemo",
                        "meta" =>  [
                            "title" =>  "Drag Dialog"
                        ]
                    ],
                    [
                        "path" =>  "drag-select",
                        "name" =>  "DragSelectDemo",
                        "meta" =>  [
                            "title" =>  "Drag Select"
                        ]
                    ],
                    [
                        "path" =>  "dnd-list",
                        "name" =>  "DndListDemo",
                        "meta" =>  [
                            "title" =>  "Dnd List"
                        ]
                    ],
                    [
                        "path" =>  "drag-kanban",
                        "name" =>  "DragKanbanDemo",
                        "meta" =>  [
                            "title" =>  "Drag Kanban"
                        ]
                    ]
                ]
            ],
            [
                "path" =>  "/charts",
                "redirect" =>  "noRedirect",
                "name" =>  "Charts",
                "meta" =>  [
                    "title" =>  "Charts",
                    "icon" =>  "chart"
                ],
                "children" =>  [
                    [
                        "path" =>  "keyboard",
                        "name" =>  "KeyboardChart",
                        "meta" =>  [
                            "title" =>  "Keyboard Chart",
                            "noCache" =>  true
                        ]
                    ],
                    [
                        "path" =>  "line",
                        "name" =>  "LineChart",
                        "meta" =>  [
                            "title" =>  "Line Chart",
                            "noCache" =>  true
                        ]
                    ],
                    [
                        "path" =>  "mix-chart",
                        "name" =>  "MixChart",
                        "meta" =>  [
                            "title" =>  "Mix Chart",
                            "noCache" =>  true
                        ]
                    ]
                ]
            ]
        ];
        return $this->success($data, '', '登录用户信息');
    }

    /**
     * @OA\Get(
     *     path="/v1/user/login-user-info",
     *     tags={"用户管理"},
     *     summary="登录用户信息",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionLoginUserInfo()
    {
        if (Yii::$app->user->isGuest) {
            return $this->fail('未登录', []);
        }else {
            return $this->success(Yii::$app->user->identity->toArray(), '', '登录用户信息');
        }
    }

    /**
     * @OA\Get(
     *     path="/v1/user/list",
     *     tags={"用户管理"},
     *     summary="用户列表",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionList() {
        return $this->success([]);
    }

    /**
     * @OA\Get(
     *     path="/v1/user/nav",
     *     tags={"用户管理"},
     *     summary="获取用户权限菜单",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionNav() {
        /*$rows = MenuModel::find()
            ->select(['id as id', 'IFNULL(parent, 0) as pid', 'name', 'route', 'order', 'data'])
            ->orderBy(['order'=>SORT_ASC])
            ->asArray()
            ->all();

        return $this->success(Func::ArrayToTree( $this->formatMenuData($rows) ));*/

        $navs = [
            [
                'path' => '/permission',
                'component' => 'Layout',
                'name' => 'permission',
                'redirect' => '/permission/page',
                'meta' => [
                    'title' => '权限管理A',
                    'icon' => 'el-icon-setting'
                ],
                'children' => [
                    [
                        'path' => 'page',
                        'component' => 'permission/page',
                        'name'=> 'page',
                        'meta' => [
                            'title'=>'路由OLD',
                            'icon'=> 'tree'
                        ]
                    ],
                    [
                        'path' => 'route',
                        'component' => 'permission/route',
                        'name'=> 'route',
                        'meta' => [
                            'title'=>'路由',
                            'icon'=> 'tree'
                        ]
                    ],
                    [
                        'path' => 'permissions',
                        'component' => 'permission/permissions',
                        'name'=> 'permissions',
                        'meta' => [
                            'title'=>'权限',
                            'icon'=> 'tree'
                        ]
                    ],
                    [
                        'path' => 'roles',
                        'component' => 'permission/roles',
                        'name'=> 'role',
                        'meta' => [
                            'title'=>'角色',
                            'icon'=> 'tree'
                        ]
                    ],
                    [
                        'path' => 'directive',
                        'component' => 'permission/directive',
                        'name'=> 'directive',
                        'meta' => [
                            'title'=>'指令',
                            'icon'=> 'tree'
                        ]
                    ],
                    [
                        'path' => 'role',
                        'component' => 'permission/role',
                        'name'=> 'role',
                        'meta' => [
                            'title'=>'规则',
                            'icon'=> 'tree'
                        ]
                    ],
                    [
                        'path' => 'menu',
                        'component' => 'permission/menu',
                        'name'=> 'menu',
                        'meta' => [
                            'title'=>'菜单',
                            'icon'=> 'tree'
                        ]
                    ]
                ]
            ],
            [
                'path' => '/tab',
                'component' => 'Layout',
                'name' => 'tab',
                'redirect' => '/tab/index',
                'meta' => [
                    'title' => 'Tab',
                    'icon' => 'tab'
                ],
                'children' => [
                    [
                        'path' => 'index',
                        'component' => 'index',
                        'name'=> 'route',
                        'meta' => [
                            'title' => 'Tab',
                            'icon' => 'tab'
                        ],
                    ]
                ]
            ],
        ];
        return $this->success($navs);
    }

    /**
     * @OA\Get(
     *     path="/v1/user/menus2",
     *     tags={"用户管理"},
     *     summary="获取用户系统菜单",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionMenus2() {
        $_items = MenuHelper::getAssignedMenu(Yii::$app->user->id, null);
        return $_items;
    }

    /**
     * @OA\Get(
     *     path="/v1/user/menu",
     *     tags={"用户管理"},
     *     summary="用户菜单",
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     )
     * )
     */
    public function actionMenu() {
        $rows = MenuModel::find()
            ->select(['id as id', 'IFNULL(parent, 0) as pid', 'name', 'route', 'order', 'data'])
            ->orderBy(['order'=>SORT_ASC])
            ->asArray()
            ->all();

        return $this->success(Func::ArrayToTree( $this->formatMenuData($rows) ));
    }
    private function formatMenuData($rows) {
        $list = [];
        foreach ($rows as $row) {
            $row['data'] = json_decode($row['data'], true);
            $list[] = $row;
        }
        return $list;
    }
}
